package com.example.android_wx.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.example.android_wx.R;
import com.example.android_wx.adapter.CircleAdapter;
import com.example.android_wx.base.App;
import com.example.android_wx.http.BaseCallBack;
import com.example.android_wx.http.CircleBean;
import com.example.android_wx.http.HttpHelp;
import com.example.android_wx.view.PullRefreshView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;


public class FavFragment extends Fragment {
    private ArrayList<CircleBean> arrayList = new ArrayList<>();
    private CircleAdapter adapter = new CircleAdapter(arrayList);


    private AppCompatImageView addImageView;
    private RecyclerView mainRecyclerView;
    private LinearLayoutCompat commitLinearLayout;
    private AppCompatTextView commitTextView;
    private AppCompatEditText commitEditText;
    private PullRefreshView mainPullRefreshView;


    private int page;
    private int position = 0;
    private String circleId = "";
    private String replyId = "";
    private String replyNickname = "";

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_fav, container, false);
        addImageView = root.findViewById(R.id.addImageView);
        commitLinearLayout = root.findViewById(R.id.commitLinearLayout);
        commitTextView = root.findViewById(R.id.commitTextView);
        commitEditText = root.findViewById(R.id.commitEditText);
        mainPullRefreshView = root.findViewById(R.id.mainPullRefreshView);


        mainPullRefreshView.setLinearLayoutManager();
        mainPullRefreshView.setAdapter(adapter);

        initEvent();


        return root;
    }



    private void initEvent() {




        //为适配器设置点击事件监听
        adapter.setOnItemClickListener(new CircleAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, CircleBean bean) {
                System.out.println(position + "|" + bean.getCircleContent() + '|' + bean.getCircleId());
                commitLinearLayout.setVisibility(View.GONE);

            }


            @Override
            public void onClickCommit(int position, CircleBean bean) {
                commitLinearLayout.setVisibility(View.VISIBLE);

                circleId = bean.getCircleId() + "";
                replyId = "-1";
                FavFragment.this.position = position;
                commitEditText.setHint("说点什么吧");
            }

            //点击删除
            @Override
            public void ondeleteClick(int position, CircleBean bean) {
                if (bean.getMemberId() == App.get().getMemberData().getMemberId()) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("确认您的选择~")
                            .setMessage("删除动态？")
                            .setCancelable(false)//此属性确定是否可以点击其他区域关闭对话
                            .setPositiveButton("确定", (dialogInterface, i) -> {
                                HttpHelp.get().ready("circle", "delete")
                                        .add("id", bean.getCircleId() + "")
                                        .get(new BaseCallBack() {
                                            @Override
                                            public void onSuccess(String data) {
                                                //取消成功之后的操作
                                                arrayList.remove(position);
                                                adapter.notifyDataSetChanged();
                                                Toast.makeText(getContext(),"删除成功",Toast.LENGTH_SHORT).show();

                                            }

                                            @Override
                                            public void onFailure(String reason) {

                                            }
                                        });
                            })
                            .setNegativeButton("取消", (dialogInterface, i) -> {

                            })
                            .show();
                }


            }


            @Override
            public void onClickCommitList(int position, int positionCommit, CircleBean.CommitDataDTO bean) {

                commitLinearLayout.setVisibility(View.VISIBLE);
                circleId = bean.getCircleId() + "";
                replyId = bean.getCommitId() + "";
                replyNickname = bean.getMemberNickname();
                FavFragment.this.position = position;
                commitEditText.setHint("回复@" + replyNickname);

            }

            //长按删除
            @Override
            public void onLongClickCommitList(int position, int positionCommit, CircleBean.CommitDataDTO bean) {

                if (bean.getMemberId() == App.get().getMemberData().getMemberId()) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("确认您的选择~")
                            .setMessage("删除评论？")
                            .setCancelable(false)//此属性确定是否可以点击其他区域关闭对话
                            .setPositiveButton("确定", (dialogInterface, i) -> {
                                HttpHelp.get().ready("circle", "deleteCommit")
                                        .add("id", bean.getCommitId() + "")
                                        .get(new BaseCallBack() {
                                            @Override
                                            public void onSuccess(String data) {
                                                arrayList.get(position).getCommitData().remove(positionCommit);
                                                adapter.notifyDataSetChanged();
                                            }

                                            @Override
                                            public void onFailure(String reason) {
                                                Toast.makeText(getContext(), reason, Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            })
                            .setNegativeButton("取消", (dialogInterface, i) -> {

                            })
                            .show();
                }
            }


            //长按动态
            @Override
            public void onLongClickdeleteList(int position, int positionCommit, CircleBean.CommitDataDTO bean) {

                if (bean.getMemberId() == App.get().getMemberData().getMemberId()) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("确认您的选择~")
                            .setMessage("删除动态？")
                            .setCancelable(false)//此属性确定是否可以点击其他区域关闭对话
                            .setPositiveButton("删除动态", (dialogInterface, i) -> {
                                HttpHelp.get().ready("circle", "delete")
                                        .add("id", bean.getCircleId() + "")
                                        .get(new BaseCallBack() {
                                            @Override
                                            public void onSuccess(String data) {
                                                //取消成功之后的操作
                                                Toast.makeText(getContext(),"删除成功",Toast.LENGTH_SHORT).show();

                                                adapter.notifyDataSetChanged();
                                            }

                                            @Override
                                            public void onFailure(String reason) {

                                            }
                                        });
                            })
                            .setNegativeButton("取消", (dialogInterface, i) -> {

                            })
                            .show();

                }



            }
        });

        commitTextView.setOnClickListener(v -> {
            String content = commitEditText.getText().toString();
            if (content.isEmpty()) {
                Toast.makeText(getContext(), "请输入评论内容", Toast.LENGTH_SHORT).show();
                return;
            }

            HttpHelp.get().ready("circle", "commit")
                    .add("id", circleId)
                    .add("reply_id", replyId)
                    .add("content", content)
                    .get(new BaseCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            commitLinearLayout.setVisibility(View.GONE);//隐藏评论区域
                            commitEditText.setText("");

                            CircleBean.CommitDataDTO commitDataDTO = new CircleBean.CommitDataDTO();
                            commitDataDTO.setCircleId(Integer.parseInt(circleId));
                            commitDataDTO.setCommitContent(content);
                            commitDataDTO.setMemberNickname(App.get().getMemberData().getMemberNickname());
                            if (!replyId.equals("-1")) {
                                commitDataDTO.setReplyId(Integer.parseInt(replyId));
                                commitDataDTO.setReplyMemberNickname(replyNickname);
                            } else {
                                commitDataDTO.setReplyId(-1);
                            }
                            arrayList.get(position).getCommitData().add(commitDataDTO);
                            adapter.notifyDataSetChanged();


                        }

                        @Override
                        public void onFailure(String reason) {
                            Toast.makeText(getContext(), reason, Toast.LENGTH_SHORT).show();
                        }
                    });

        });


        mainPullRefreshView.setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                arrayList.clear();
                adapter.notifyDataSetChanged();
                mainPullRefreshView.setCanLoadMore(true);

            }

            @Override
            public void onLoadMore() {


            }
        });

        mainPullRefreshView.setOnClickListener(view -> {
            //如果没有数据则执行读取数据的方法
            if (mainPullRefreshView.isError() || arrayList.size() == 0) {
                page = 1;

            }
        });




        mainPullRefreshView.setLoad();
        CountDownTimer countDownTimer = new CountDownTimer(800,200) {
            @Override
            public void onTick(long millisUntilFinished) {
                System.out.println(System.currentTimeMillis());
            }

            @Override
            public void onFinish() {


                HttpHelp.get().ready("circle", "GetCollectionlist")
                        .add("page", page+"")
                        .add("id",App.get().getMemberData().getMemberId()+"")
                        .get(new BaseCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                try {
                                    JSONArray jsonArray = new JSONArray(data);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        arrayList.add(new Gson().fromJson(jsonArray.getString(i), CircleBean.class));
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (jsonArray.length() == 20) {
                                        page++;
                                    }else {
                                        mainPullRefreshView.setCanLoadMore(false);
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                mainPullRefreshView.setComplete();
                            }

                            @Override
                            public void onFailure(String reason) {

                                if (arrayList.size()==0){
                                    mainPullRefreshView.setError(reason);
                                }else {
                                    Toast.makeText(getContext(), reason, Toast.LENGTH_SHORT).show();
                                }


                            }
                        });


            }
        }.start();



    }



}


